package com.lier.gulimall.product.web;

import com.lier.common.vo.Catalog2VO;
import com.lier.gulimall.product.entity.CategoryEntity;
import com.lier.gulimall.product.service.CategoryService;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;
//    @Autowired
//    RedissonClient redissonClient;

    @GetMapping({"/", "index.html"})
    public String indexPage(Model model) {

        List<CategoryEntity> categoryEntitys = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", categoryEntitys);
        return "index";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catalog2VO>> getCatalogJson() {
        return categoryService.getCatalogData();
    }

    /**
     * 测试redisson实现分布式锁
     */
//    @ResponseBody
//    @GetMapping("/testRedisson")
//    public String test() {
//        // 1.获取锁
//        RLock lock = redissonClient.getLock("redisson_lock");
//
//        // 2.加锁
//        // 1）锁自动续期+30S，业务超长情况下（看门狗）
//        // 2）如果线程宕机，看门狗不会自动续期，锁会自动过期
//        // 3）unlock使用lua脚本释放锁，不会出现误删锁
//        lock.lock(10, TimeUnit.SECONDS);
//
//        try {
//            // 加锁成功，执行业务
//            System.out.println("加锁成功，执行业务..." + Thread.currentThread().getId());
//            Thread.sleep(30000);
//        } catch (Exception e) {
//
//        } finally {
//            // 3.解锁
//            System.out.println("解锁..." + Thread.currentThread().getId());
//            lock.unlock();
//        }
//        return "testRedisson";
//    }

    /**
     * 测试redisson实现分布式锁
     */
//    @ResponseBody
//    @GetMapping("/testRedisson2")
//    public String test2() {
//        // 1.获取锁
//        RReadWriteLock lock = redissonClient.getReadWriteLock("redisson_lock");
//
//        // 2.加锁
//        // 1）锁自动续期+30S，业务超长情况下（看门狗）
//        // 2）如果线程宕机，看门狗不会自动续期，锁会自动过期
//        // 3）unlock使用lua脚本释放锁，不会出现误删锁
//        RLock readLock = lock.readLock();
//        readLock.lock(10, TimeUnit.SECONDS);
//        try {
//            // 加锁成功，执行业务
//            System.out.println("加锁成功，执行业务..." + Thread.currentThread().getId());
//            Thread.sleep(30000);
//        } catch (Exception e) {
//
//        } finally {
//            // 3.解锁
//            System.out.println("解锁..." + Thread.currentThread().getId());
//            readLock.unlock();
//        }
//        return "testRedisson";
//    }



    @Resource
    private RedissonClient redissonClient;

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("/write")
    @ResponseBody
    public String write() {

        System.out.println("写当前线程ID：" + Thread.currentThread().getId());

        // 添加写锁
        RLock writeLock = redissonClient.getReadWriteLock("rw-lock").writeLock();
        String uuid = "";
        try {
            System.out.println("写锁加锁");
            writeLock.lock();
            uuid = UUID.randomUUID().toString();
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("uuid", uuid);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            System.out.println("写锁释放锁");
            writeLock.unlock();
        }

        return uuid;
    }

    @GetMapping("/read")
    @ResponseBody
    public String read() {

        System.out.println("读当前线程ID：" + Thread.currentThread().getId());

        RLock readLock = redissonClient.getReadWriteLock("rw-lock").readLock();
        String uuid = "";
        try {
            System.out.println("读锁加锁");
            readLock.lock();
            uuid =  stringRedisTemplate.opsForValue().get("uuid");
        } finally {
            System.out.println("读锁释放锁");
            readLock.unlock();
        }

        return uuid;
    }

}
